采用visionpro工具连接相机采集图像,语言c#
这是一个项目的简单Demo,只有采图和显示部分
using Cognex.VisionPro;using Cognex.VisionPro.Exceptions;using Cognex.VisionPro.ToolBlock;using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace AcqFifoTool{ public partial class Form1 : Form { CogAcqFifoTool mAcqFifoTool; private bool m_Grab = false; public static Thread CamGrabThread1; public static Thread CamGrabThread2; private ManualResetEvent _muanualEven = new ManualResetEvent(false); byte[] imgByte;//用于加载和转换图像,以流的方式转化 CogImage8Grey currentImage = null; public Form1() { InitializeComponent(); //加载相机1 toolblock cogToolBlockEditV21.Subject = CogSerializer.LoadObjectFromFile(Application.StartupPath @"\VPP\CogAcqFifoToolBlock1.vpp") as CogToolBlock; cogToolBlockEditV21.Subject.Ran = new EventHandler(Subject_Ran1); } private void Form1_Load(object sender, EventArgs e) { cogToolBlockEditV21.LocalDisplayVisible = true; cogToolBlockEditV21.SubjectChanged = new EventHandler(cogToolBlockEditV21_SubjectChanged); mAcqFifoTool = cogToolBlockEditV21.Subject.Tools["CogAcqFifoTool1"] as CogAcqFifoTool; } void Subject_Ran1(object sender, EventArgs e) { cogRecordDisplay1.Image = cogToolBlockEditV21.Subject.Outputs["Output"].Value as CogImage8Grey; } private void cogToolBlockEditV21_SubjectChanged(object sender, EventArgs e) { } private void startBtn_Click(object sender, EventArgs e) { startBtn.BackColor = Color.Orange; try { if (mAcqFifoTool.Operator == null) { MessageBox.Show("请先初始化相机"); startBtn.BackColor = Color.Transparent; return; } m_Grab = !m_Grab; if (m_Grab) { startBtn.Text = "停止采集"; if (CamGrabThread1 == null) { CamGrabThread1 = new Thread(new ThreadStart(CamContinueGrabProc1)); CamGrabThread1.Start(); _muanualEven.Set(); } else if (CamGrabThread1.ThreadState == System.Threading.ThreadState.WaitSleepJoin) { _muanualEven.Set(); } } else { _muanualEven.Reset(); startBtn.Text = "开始采集"; startBtn.BackColor = Color.Transparent; } } catch (CogException ex) { _muanualEven.Reset(); MessageBox.Show("连续采集异常"); } } private void CamContinueGrabProc1() { while (true) { try { _muanualEven.WaitOne(); GetImage(out currentImage); ShowImage(currentImage); Application.DoEvents(); Thread.Sleep(50); } catch (CogException cogEc) { MessageBox.Show("连续采集异常"); } } } public void GetImage(out CogImage8Grey image) { image = null; mAcqFifoTool.Run(); image = mAcqFifoTool.OutputImage as CogImage8Grey; } private void ShowImage(CogImage8Grey objImage) { //grabberForm.CogRecordDisplay1.DrawingEnabled = false; cogRecordDisplay1.Image = objImage; cogRecordDisplay1.Fit(); //grabberForm.CogRecordDisplay1.DrawingEnabled = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //当toolblock改变时保存到vpp CogSerializer.SaveObjectToFile(cogToolBlockEditV21.Subject, Application.StartupPath @"\VPP\CogAcqFifoToolBlock1.vpp"); } }}
评论